package java8.xml.dom4j;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;

/**
 * @author 周宇
 * @create 2020-08-28 11:09
 */
public class WriteXML {
    public static void main(String[] args) throws Exception {
        // 创建一个XMLWriter对象
        OutputFormat format = OutputFormat.createPrettyPrint();
        XMLWriter writer = new XMLWriter(new FileOutputStream("src/main/resources/xml/students2.xml"), format);
        // 生成一个新的Document对象
        Document doc = DocumentHelper.createDocument();
        // 增加Students元素节点
        Element students = doc.addElement("Students");
        // 增加两个Student元素节点
        Element student1 = students.addElement("student");
        Element student2 = students.addElement("student");
        // 为两个Student元素节点分别增加id属性节点
        student1.addAttribute("id", "001");
        student2.addAttribute("id", "002");
        // 分别增加name age gender grade 元素子节点
        student1.addElement("name").setText("张三");
        student1.addElement("age").setText("19");
        student1.addElement("gender").setText("男");
        student1.addElement("grade").setText("计算机1班");

        student2.addElement("name").setText("李四");
        student2.addElement("age").setText("20");
        student2.addElement("gender").setText("男");
        student2.addElement("grade").setText("计算机2班");
        // 将Document对象写入磁盘
        writer.write(doc);
        writer.close();
    }
}
